﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text.RegularExpressions;
using HAF.FoundationLib;
using Newtonsoft.Json;
using WareDealer.Helper;
using WareDealer.Mode;

namespace WareDealer.Works
{
    /// <summary>
    /// 库存采集任务
    /// </summary>
    [DisplayName("库存采集工作项")]
    public class JdStockWork : JdWorkItem
    {
        /// <summary>
        /// 最大处理数量
        /// </summary>
        private const int StockMaxLength = 30;

        readonly List<WareStock> _batchWareStocks = new List<WareStock>();
        /// <summary>
        /// 执行函数
        /// </summary>
        public override void ExecItem()
        {
            List<ProductInfo> wares = WorkItems as List<ProductInfo>;
            if (wares == null || wares.Count <= 0) return;
            Statu = EnumGatherStatu.Begin;
            List<string> wStockIds = new List<string>();
            int i = 0;
            //var wStocks = WorkItems.Select(item => GetWareStock(item.ProductID, item.VenderId, item.Catalog)).Where(rtnStock => rtnStock != null).ToList();
            foreach (var item in wares)
            {
                if (i >= StockMaxLength)
                {
                    List<WareStock> wStocks = GetBatchWareStock(wStockIds);
                    if (wStocks != null && wStocks.Count > 0)
                    {
                        _batchWareStocks.AddRange(wStocks);
                    }
                    i = 0;
                    wStockIds.Clear();
                }
                wStockIds.Add(item.ProductID);
                i++;
                //WareStock rtnStock = GetWareStock(item.ProductID, item.VenderId, item.Catalog);
                //if (rtnStock != null)
                //{
                //    wStocks.Add(rtnStock);
                //}

            }
            //可能存在少于30的情况
            List<WareStock> wStocks1 = GetBatchWareStock(wStockIds);
            _batchWareStocks.AddRange(wStocks1);

            ResultItems = _batchWareStocks;
        }

        /// <summary>
        /// 获取库存信息
        /// </summary>
        /// <param name="skuId">商品编号</param>
        /// <param name="venderId">商家编号</param>
        /// <param name="category">分类</param>
        /// <returns></returns>
        private WareStock GetWareStock(string skuId, string venderId, string category)
        {
            try
            {
                WareStock rtnStock = null;
                //配送服务 22_1930_4283_0
                if (string.IsNullOrEmpty(category))
                {
                    category = "6144,12041,12047";
                }
                //http://ss.3.cn/ss/areaStockState/mget?app=search_pc&ch=1&skuNum=11968160;1069555;1510479;1601978;206737&area=22,1930,4283,0&callback=jQuery966382&_=1467106314590
                string urlService = "http://c0.3.cn/stock?skuId=" + skuId + "&venderId=" + venderId.Trim() + "&cat=" + category + "&area=" + SysParams.DispathArea
                    + "&buyNum=1&extraParam={%22originid%22:%221%22}&ch=1";

                string htmlService = HttpHelper.GetResponseGBK(urlService, "get", string.Empty);
                string strStock = htmlService.Replace("getStockCallback(", "").TrimEnd(')');
                if (string.IsNullOrEmpty(strStock))
                {
                    return null;
                }
                StockInfo jdStock = JsonConvert.DeserializeObject<StockInfo>(strStock);
                if (jdStock != null)
                {
                    rtnStock = new WareStock()
                    {
                        Skuid = skuId,
                        StockState = jdStock.Stock.StockState,
                        StockName = jdStock.Stock.StockStateName,
                        StockNum = jdStock.Stock.rn
                    };

                }
                return rtnStock;
            }
            catch (Exception ex)
            {
                Faster.XLogErr(ex.Message);
                return null;
            }

        }
        /// <summary>
        /// 批量获取库存信息
        /// </summary>
        /// <returns></returns>
        private List<WareStock> GetBatchWareStock(List<string> pids)
        {
            try
            {
                List<WareStock> rtnStocks = new List<WareStock>();
                Faster.XLogInfo(string.Format("批量采集库存{0}更新开始", Name));

                //http://ss.3.cn/ss/areaStockState/mget?app=search_pc&ch=1&skuNum=11968160;1069555;1510479;1601978;206737&area=22,1930,4283,0&callback=jQuery966382&_=1467106314590
                //http://ss.3.cn/ss/areaStockState/mget?app=list_pc&ch=1&skuNum=11968160;1069555;1510479;1601978;206737&area=22,1930,4283,0&callback=jQuery966382&_=1467106314590
                //[{"id":"1309453","p":"209.00","m":"328.00"},{"id":"1713088","p":"118.00","m":"208.00"},{"id":"1191695","p":"148.00","m":"268.00"}]
                if (pids != null && pids.Count > 0)
                {
                    try
                    {
                        Statu = EnumGatherStatu.Exec;
                        string skuids = string.Join(";", pids.ToArray());
                        string myArea = SysParams.DispathArea.Replace('_', ',');
                        string url = string.Format("http://ss.3.cn/ss/areaStockState/mget?app=search_pc&ch=1&skuNum={0}&area={1}&_={2}", skuids, myArea, Golemer.GetTimeStamp(false));
                        //{"1069555":{"a":"34","b":"1","c":"-1","l":"0"},"11968160":{"a":"40","b":"1","c":"-1","l":"2"},
                        //"1510479":{"a":"33","b":"1","c":"-1","l":"0"},"1601978":{"a":"33","b":"1","c":"-1","l":"0"},"206737":{"a":"34","b":"1","c":"-1","l":"0"}}
                        string mystock = HttpHelper.GetResponseUTF(url, "get", string.Empty);
                        //string[] stocks = Regex.Split(mystock, "},", RegexOptions.IgnoreCase);
                        string[] stocks = mystock.Split(new string[] { "}," }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var item in stocks)
                        {
                            string skuId = Regex.Match(item, "(\\d{6,14})").Value;
                            string tJsonTxt = Regex.Match(item, "\\{\"a.*").Value;
                            string cont = tJsonTxt.Replace("}}", "") + "}";
                            AreaStockState jdStock = JsonConvert.DeserializeObject<AreaStockState>(cont);

                            var rtnStock = new WareStock()
                            {
                                Skuid = skuId,
                                StockState = int.Parse(jdStock.a),
                                //StockName = jdStock.Stock.StockStateName,
                                StockNum = int.Parse(jdStock.l)
                            };
                            rtnStocks.Add(rtnStock);
                        }
                    }
                    catch (Exception ex)
                    {
                        Faster.XLogErr(ex.Message);
                    }
                }
                Statu = EnumGatherStatu.End;
                Faster.XLogInfo(string.Format("批量采集库存{0}更新结束", Name));
                return rtnStocks;
            }
            catch (Exception ex)
            {
                Statu = EnumGatherStatu.End;
                Faster.XLogErr(ex.Message);
                return null;
            }
        }

        public class AreaStockState
        {
            /// <summary>
            /// 库存状态
            /// </summary>
            /// <remarks>33 有货、34 无货、36 预订</remarks>
            public string a { get; set; }
            /// <summary>
            /// 1
            /// </summary>
            public string b { get; set; }
            /// <summary>
            /// 库存余量 -1、2、3、5
            /// </summary>
            public string c { get; set; }
            /// <summary>
            /// 到货日期
            /// </summary>
            public string j { get; set; }
            /// <summary>
            /// 0
            /// </summary>
            public string l { get; set; }
        }
    }
}
